package com.globallogic.restdemo.resources;

import com.globallogic.restdemo.dao.UserDao;
import com.globallogic.restdemo.dto.User;
import com.globallogic.restdemo.services.UserService;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.bind.JAXBElement;
import java.util.ArrayList;
import java.util.List;

@Path("/users")
public class UserResource {

    private UserService userService;

    public UserResource(){
        userService = new UserService();
    }

    @GET
    @Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_XML})
    public List<User> getAllUsers(){
        List<User> users = new ArrayList<User>();
        users.addAll(userService.getAllUsers());
        return users;
    }

    @GET
    @Path("{userId}")
    @Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_XML})
    public Response getUserById(@PathParam("userId") long id){
        User user = userService.getUserById(id);

        if (user == null)
            return Response.ok("No user with this id.").build();
        return Response.ok(user, MediaType.APPLICATION_JSON).build();
    }

    @POST
    @Path("/add")
    @Consumes(MediaType.APPLICATION_JSON)
    public void addUser(JAXBElement<User> userJAXB){
        User user = userJAXB.getValue();
        userService.addUser(user);
    }

    @PUT
    @Path("/update")
    @Consumes(MediaType.APPLICATION_JSON)
    public void updateUser(JAXBElement<User> userJAXB){
        User user = userJAXB.getValue();
        userService.updateUser(user);
    }

    @DELETE
    @Path("/remove/{userId}")
    public void removeUser(@PathParam("userId") long id){
        userService.removeUserById(id);
    }

    @DELETE
    @Path("/remove-all")
    public void removeAllUser(){
        userService.removeAllUsers();
    }

}
